package com.bsit.obu.business;

import android.os.AsyncTask;
import android.text.TextUtils;

import com.bsit.obu.base.BaseApplication;
import com.bsit.obu.callback.RequestCallBack;
import com.bsit.obu.constant.Constants;
import com.bsit.obu.utils.ByteUtil;
import com.bsit.obu.utils.CommonUtil;
import com.bsit.obu.utils.MyLog;
import com.bsit.obu.utils.SPUtils;
import com.tianyuxinghang.sxmobileterm.dsrc.DsrcBusinesss;

import java.io.BufferedInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.ArrayList;


public class SocketBusiness {
    //类初始化时，不初始化这个对象(延时加载，真正用的时候再创建)
    private static SocketBusiness instance;
    private static Socket socket;

    //构造器私有化
    private SocketBusiness() {
    }

    //方法同步，调用效率低
    public static synchronized SocketBusiness getInstance() {
        if (instance == null) {
            instance = new SocketBusiness();
        }
        return instance;
    }
    public void closeConnection(){
        try {
           // MyLog.d(MyLog.TAG,"socket1---------"+socket);
            if(socket!=null){
                if(!socket.isClosed()||socket.isConnected()){
                    socket.close();
                }
                socket=null;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    private class MyTask extends AsyncTask<byte[], Integer, byte[]> {
        private RequestCallBack requestCallBack;

        public MyTask(RequestCallBack requestCallBack) {
            this.requestCallBack = requestCallBack;
        }

        @Override
        protected byte[] doInBackground(byte[]... bytes) {
            try {

                // 1、创建客户端Socket，指定服务器地址和端口
                String ip = Constants.SOCKET_IP;
                int port = Constants.SOCKET_PROT;

                String mIP = (String) SPUtils.get(BaseApplication.getInstance(),"ip","");
                String mPort = (String) SPUtils.get(BaseApplication.getInstance(),"port","");
                if(!TextUtils.isEmpty(mIP)&&!TextUtils.isEmpty(mPort)){
                    ip = mIP;
                    port = Integer.valueOf(mPort);
                }
                if (null == socket) {
                    //  MyLog.e(MyLog.TAG, "ip : " + ip + "-------port ---- :" + port);
                    socket = new Socket(ip, port);
                }
                MyLog.e(MyLog.TAG, "KeepAlive == " + socket .getKeepAlive());
                // 2、获取输出流，向服务器端发送信息
                OutputStream os = new DataOutputStream(socket.getOutputStream());
                // 从服务器接收返回的数据
                //   BufferedReader input = new BufferedReader(new InputStreamReader(socket.getInputStream(),"UTF-8"));
                BufferedInputStream in = new BufferedInputStream(
                        socket.getInputStream());
                socket.setSoTimeout(5 * 1000);
                socket.setKeepAlive(true);
                // 3、传送给服务器
                os.write(bytes[0]);
                os.flush();
                MyLog.e(MyLog.TAG, "  os.flush()------------------------------->" );
                byte[] receiveBytes = new byte[1024 * 4];
                // 定义一个长度为8K字节的数组用来存放服务器返回的结果
                byte[] bufferedBytes = new byte[1024 * 4];
                int len = 0;
                int lastLen = 0;
                if ((len = in.read(receiveBytes)) != -1) {
                    System.arraycopy(receiveBytes, 0, bufferedBytes, lastLen, len);
                    lastLen += len;
                }
                byte[] returnBytes = new byte[lastLen];
                System.arraycopy(bufferedBytes, 0, returnBytes, 0,
                        returnBytes.length);

                // 判断当前是否处于连接0834
                boolean isConnection = socket.isConnected() && !socket.isClosed();
                MyLog.e(MyLog.TAG, "isConnection == " +isConnection);
                if (!isConnection) {
                    socket.close();
                    return new byte[1];
                }
                return returnBytes;
            } catch (UnknownHostException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(byte[] datas) {
            super.onPostExecute(datas);
            if(datas!=null&&datas.length==1){
                requestCallBack.error(Constants.ERROR_CODE,"网络已断开，请重新连接");
                return;
            }
            if(datas!=null&&datas.length>0){
                String responseData = ByteUtil.byte2HexStr(datas);
                MyLog.d(MyLog.TAG,"responseData=="+responseData);
                //F5F5 11 000A 0000 0F090E0501080B01 5550 5F
                //                  09080E0D0E01000E BFAC 5F
                if(responseData.startsWith("F5F5")){
                    String statusCode =  responseData.substring(10,14);
                    if(statusCode.equals("0000")){
                        String finalResult = responseData.substring(14);
                        MyLog.d(MyLog.TAG,"success=="+finalResult);
                        requestCallBack.next(statusCode,finalResult);
                    }else{
                        String finalResult = "";
                        if(responseData.length()>14){
                             finalResult = responseData.substring(14);
                            MyLog.d(MyLog.TAG,"error=="+finalResult);
                        }
                        requestCallBack.error(statusCode,finalResult);
                    }
                }
            }else{
                requestCallBack.error(Constants.ERROR_CODE,"网络异常，请稍后再试");
            }

        }
    }


    public void requestData(String cmd, String data, RequestCallBack requestCallBack) {
        String crcData = cmd + CommonUtil.getDataLen(data) +data;
        int crcResult = DsrcBusinesss.getInstance().getCrc(crcData,crcData.length());
        // MyLog.d(MyLog.TAG,"crcData=="+crcData+"\ncrcResult=="+crcResult);
         MyLog.d(MyLog.TAG,String.format( "crcResult==%04x", crcResult ));
         String requestData = "F5F5" + crcData +String.format( "%04x", crcResult ) + "5F";
         MyLog.d(MyLog.TAG,"requestData=="+requestData);
         new MyTask(requestCallBack).execute(ByteUtil.hexStr(requestData));
    }
}
